<template>
    <div class="personal-center">
        <div class="profile-header">
            <div class="avatar-uploader">
                <el-upload class="avatar-upload" :show-file-list="false" :http-request="handleUpload"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="userInfo.imagePath" :src="userInfo.imagePath" class="avatar" />
                    <el-icon v-else class="avatar-icon">
                        <User />
                    </el-icon>
                    <div class="avatar-edit-tip">点击更换头像</div>
                </el-upload>
            </div>
            <div class="profile-basic">
                <h2>{{ userInfo.realName || userInfo.userName }}</h2>
                <p class="user-role">
                    <el-tag :type="getRoleType(userInfo.role)">{{ getRoleName(userInfo.role) }}</el-tag>
                </p>
                <p class="last-active">最后活动时间: {{ userInfo.lastActiveTime || '暂无记录' }}</p>
            </div>
        </div>

        <el-divider />

        <div class="profile-details">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="用户名">{{ userInfo.userName }}</el-descriptions-item>
                <el-descriptions-item label="用户ID">{{ userInfo.id }}</el-descriptions-item>
                <el-descriptions-item label="年龄">{{ userInfo.age }}</el-descriptions-item>
                <el-descriptions-item label="性别">
                    {{ userInfo.sex === 1 ? '男' : userInfo.sex === 2 ? '女' : '未知' }}
                </el-descriptions-item>
                <el-descriptions-item label="出生日期">{{ userInfo.birthDay }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo.phone || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ userInfo.createTime }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
                        {{ userInfo.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </el-descriptions-item>
            </el-descriptions>
        </div>

        <div class="profile-actions">
            <el-button type="primary" @click="showEditDialog = true">编辑信息</el-button>
        </div>

        <!-- 编辑信息对话框 -->
        <el-dialog v-model="showEditDialog" title="编辑个人信息" width="50%">
            <el-form :model="userInfo" label-width="100px" :rules="rules" ref="editFormRef">
                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="userInfo.realName" />
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="userInfo.age" :min="1" :max="120" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userInfo.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthDay">
                    <el-date-picker v-model="userInfo.birthDay" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择日期时间" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="userInfo.phone" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showEditDialog = false">取 消</el-button>
                    <el-button type="primary" @click="submitEditForm">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue';
import { getCurrentUser, updateUser, uploadFile } from '@/api/user';
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()



// 用户信息
const userInfo = ref({
    id: 0,
    userUuid: '',
    userName: '',
    realName: '',
    age: 0,
    role: 0,
    sex: null,
    birthDay: '',
    phone: null,
    lastActiveTime: '',
    createTime: '',
    modifyTime: '',
    status: null,
    userLevel: null,
    imagePath: null
});

// 编辑
const showEditDialog = ref(false);
const editFormRef = ref();

// 表单验证规则
const rules = {
    realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
};

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        const res = await getCurrentUser({
            _t: Date.now()
        });
        if (res.code == 1) {
            userInfo.value = res.response;
            userStore.setUserInfo({
                username: res.response.userName,
                avatar: res.response.imagePath
            })
            console.log("请求用户:", userInfo.value);
        }
    } catch (error) {
        ElMessage.error('获取用户信息失败');
    }
};

// 角色名称映射
const getRoleName = (role) => {
    const roles = {
        1: '学生',
        2: '教师',
        3: '管理员'
    };
    return roles[role] || '未知角色';
};

// 角色标签类型映射
const getRoleType = (role) => {
    const types = {
        1: 'success',
        2: 'warning',
        3: 'danger'
    };
    return types[role] || 'info';
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
    const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

// 自定义上传方法
const handleUpload = async (options) => {
    try {
        const res = await uploadFile(options.file);
        if (res.code == 1) {
            const updatedUser = {
                ...userInfo.value,
                imagePath: res.url,
                modifyTime: new Date().toISOString()
            };
            await updateUser(updatedUser);
            userInfo.value = updatedUser;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('头像上传失败');
        }
    } catch (error) {
        ElMessage.error('头像上传失败');
    }
};

// 提交编辑表单
const submitEditForm = async () => {
    try {
        // 验证表单
        await editFormRef.value.validate();

        // 准备完整用户数据
        const updatedUser = {
            ...userInfo.value,
            modifyTime: new Date().toISOString()
        };

        // 调用API更新
        const res = await updateUser(updatedUser);
        if (res.code == 1) {
            ElMessage.success('个人信息更新成功');
            showEditDialog.value = false;
            console.log(userInfo.value);
            await fetchUserInfo();

        } else {
            ElMessage.error('个人信息更新失败');
        }
    } catch (error) {
        if (error?.errors) {
            return;
        }
        ElMessage.error('个人信息更新失败');
    }
};

// 初始化获取用户信息
onMounted(() => {
    fetchUserInfo();
});
</script>

<style scoped>
.personal-center {
    padding: 20px 0 20px 0;
    max-width: 1200px;
    margin: 0 auto;
}

.profile-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.profile-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.avatar-uploader {
    margin-right: 30px;
    text-align: center;
}

.avatar-upload {
    position: relative;
    cursor: pointer;
}

.avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #eee;
}

.avatar-icon {
    font-size: 120px;
    color: #c0c4cc;
    border-radius: 50%;
    background-color: #f5f7fa;
    padding: 10px;
}

.avatar-edit-tip {
    margin-top: 10px;
    color: #999;
    font-size: 14px;
}

.profile-basic h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
}

.user-role {
    margin: 5px 0;
}

.last-active {
    color: #909399;
    font-size: 14px;
    margin: 10px 0 0 0;
}

.profile-details {
    margin: 20px 0;
}

.profile-actions {
    margin-top: 20px;
    text-align: center;
}

.el-descriptions-item__label {
    width: 100px;
}
</style>